package com.mdd.common.dynamicdatasource.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mdd.common.dynamicdatasource.context.DynamicDataSourceContextHolder;
import com.mdd.common.dynamicdatasource.entity.TenantInfo;
import com.mdd.common.dynamicdatasource.mapper.TenantMapper;
import com.mdd.common.dynamicdatasource.service.ITenantInfoService;
import com.mdd.common.exception.OperateException;
import com.mdd.common.util.Constants;
import com.mdd.common.util.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;

//@Service
public class ITenantInfoServiceImpl implements ITenantInfoService {
    @Resource
    TenantMapper tenantMapper;

    @Override
    public List<TenantInfo> getAllList() {
        QueryWrapper<TenantInfo> wrapper = new QueryWrapper<>();
        List<TenantInfo> tenantInfos = tenantMapper.selectList(wrapper);
        return tenantInfos;
    }

    @Override
    public void checkTenantInfo(String tenantId) {
        DynamicDataSourceContextHolder.setDataSourceKey(Constants.MAIN_TENANT_ID);
        LambdaQueryWrapper<TenantInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(tenantId), TenantInfo::getTenantId, tenantId).last("limit 1");
        TenantInfo tenantInfo = tenantMapper.selectOne(wrapper);
        Assert.notNull(tenantInfo, "应用不存在");
        DynamicDataSourceContextHolder.setDataSourceKey(tenantId);
        long endTime = tenantInfo.getEndTime().getTime();
        if (endTime < System.currentTimeMillis()) {
            throw new OperateException("应用授权已经过期，请联系客服！");
        }
    }
}
